<template>
  <div>
    <h3>商家管理 - 修改店铺信息</h3>
    <el-form :model="merchantReviseDto" ref="merchantReviseForm" label-width="120px" :rules="rules">
      <el-form-item label="选择店铺" prop="id">
        <el-select v-model="merchantReviseDto.id" placeholder="请选择要修改的店铺" @change="onStoreChange">
          <el-option
              v-for="store in merchantList"
              :key="store.id"
              :label="store.shopName"
              :value="store.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="merchantReviseDto.shopName" placeholder="请输入店铺名称"></el-input>
      </el-form-item>
      <el-form-item label="店铺地址" prop="address">
        <el-input v-model="merchantReviseDto.address" placeholder="请输入店铺地址"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input v-model="merchantReviseDto.contactPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="店铺头像">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="customUpload"
        >
          <div class="avatar-wrapper">
            <img
                v-if="merchantReviseDto.shopAvatar"
                :src="merchantReviseDto.shopAvatar"
                class="avatar-image"
            />
            <div v-else class="avatar-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">上传店铺头像</span>
            </div>
            <div class="upload-mask">
              <el-icon class="upload-icon"><Edit /></el-icon>
              <span class="upload-text">更换头像</span>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reviseStore">修改店铺信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { Plus, Edit } from '@element-plus/icons-vue'

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('user');
const user = userStr ? JSON.parse(userStr) : null;

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 定义表单数据
const merchantReviseDto = ref({
  id: null,
  shopName: '',
  address: '',
  contactPhone: '',
  shopAvatar: '',
  userId: user?.id || null,
  updateTime: new Date()
});

// 存储店铺列表
const merchantList = ref([]);

// 表单验证规则
const rules = reactive({
  id: [
    { required: true, message: '请选择要修改的店铺', trigger: 'change' }
  ],
  shopName: [
    { min: 2, max: 100, message: '店铺名称长度在 2 - 100 个字符之间', trigger: 'blur' }
  ],
  address: [
    { max: 255, message: '店铺地址不能超过 255 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
});

// 表单引用
const merchantReviseForm = ref(null);

// 自定义上传
const customUpload = async (options) => {
  const { file } = options;
  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', user?.id || '123');

    const response = await axios.post(`${BASE_URL}/v1/file/upload`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${user?.token || ''}`
      }
    });

    if (response.data.code === 2000) {
      ElMessage.success('头像上传成功');
      merchantReviseDto.value.shopAvatar = response.data.data;
    } else {
      throw new Error(response.data.message || '上传失败');
    }
  } catch (error) {
    ElMessage.error('上传出错：' + error.message);
    throw error;
  }
};

// 上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }

  return isImage && isLt5M;
};

// 获取店铺列表
const selStore = async () => {
  try {
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取店铺列表失败');
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error);
    ElMessage.error('获取店铺列表失败，请稍后重试');
  }
};

// 店铺选择变更时填充表单数据
const onStoreChange = (storeId) => {
  if (!storeId) return;

  const selectedStore = merchantList.value.find(store => store.id === storeId);
  if (selectedStore) {
    merchantReviseDto.value = {
      ...selectedStore,
      userId: user?.id || null,
      updateTime: new Date()
    };
  }
};

// 定义修改店铺信息方法
const reviseStore = async () => {
  // 表单验证
  merchantReviseForm.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请完善店铺信息');
      return;
    }

    // 如果没有上传头像，使用默认头像
    if (!merchantReviseDto.value.shopAvatar) {
      merchantReviseDto.value.shopAvatar = defaultAvatar;
    }

    // 发送修改店铺信息请求
    axios.post(`${BASE_URL}/api/v1/merchant/reviseStore`, merchantReviseDto.value, {
      withCredentials: true
    })
        .then(response => {
          if (response.data.code === 2000) {
            ElMessage.success('店铺信息修改成功');
            // 清空表单
            merchantReviseDto.value = {
              id: null,
              shopName: '',
              address: '',
              contactPhone: '',
              shopAvatar: '',
              userId: user?.id || null,
              updateTime: new Date()
            };
            // 重新获取店铺列表
            selStore();
          } else {
            ElMessage.error(response.data.msg || '修改店铺信息失败');
          }
        })
        .catch(error => {
          console.error('修改店铺信息失败:', error);
          ElMessage.error('修改店铺信息失败，请稍后重试');
        });
  });
};

// 页面挂载时获取店铺列表
onMounted(() => {
  selStore();
});
</script>

<style scoped>
.avatar-uploader {
  --el-avatar-size: 178px;
}

.avatar-wrapper {
  position: relative;
  width: var(--el-avatar-size);
  height: var(--el-avatar-size);
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed var(--el-border-color);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  background-color: #f5f7fa;
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-wrapper:hover .upload-mask {
  opacity: 1;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}
</style>